package com.ncmmall.mall.controller.business.marketing;

import com.alibaba.excel.metadata.BaseRowModel;
import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.lang.Dates;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.marketing.seckill.BargainGoods;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.controller.utils.excel.ExcelUtil;
import com.ncmmall.mall.params.BargainDTO;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 特价活动管理
 *
 * @author linxs
 * @date 2020-01-17 23:13
 */
@Slf4j
@Controller
@RequestMapping(value = "/mall/bargain")
public class BargainController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsApplication goodsApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 特价活动管理
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, Goods goods) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = new HashMap<>();
        QueryPage<Goods> page;

        if (goods.getBargainStatus() == 6) {
            QueryPage<BargainGoods> page2 = queryChannelService.findPage("select b from BargainGoods b order by b.endDateOfValidity desc", pageRequest.setParams(params), BargainGoods.class);
            List<Goods> goodsList = new ArrayList<>();

            for (BargainGoods bargainGoods : page2.getResult()) {
                Goods g = bargainGoods.getGoods();
                g.setBargainPrice(bargainGoods.getBargainPrice());
                g.setBargainSalesVolume(bargainGoods.getBargainSalesVolume());
                g.setBargainStore(bargainGoods.getBargainStore());
                g.setBargainStatus(6);
                goodsList.add(g);
            }
            page = new QueryPage<>(page2.getTotalCount(), goodsList, page2.getPageNo(), page2.getPageSize());
        } else {
            String hql = builderSQL("select u from Goods u where u.marketingType = 1 and u.bargainStatus not in (1) ", params, goods);
            page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);
        }

        model.addAttribute("page", page)
                .addAttribute("params", goods)
                .addAttribute("channels", queryChannelService.findAll(QGoodsChannel.goodsChannel.status.eq(2).and(QGoodsChannel.goodsChannel.level.eq(1)).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0)), GoodsChannel.class));

        return "mall/marketing/bargain/list";
    }


    /**
     * 导出Excel
     */
    @RequestMapping(value = "/exports", method = RequestMethod.GET)
    public void exports(HttpServletResponse response, Goods goods) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            Map<String, Object> params = Maps.newHashMap();
            String hql = builderSQL("select u from Goods u where u.marketingType = 1 and u.bargainStatus not in (1,7) ", params, goods);

            List<Goods> result = queryChannelService.findAll(hql, map, Goods.class);
            List<BaseRowModel> data = new ArrayList<>(result.size());

            for (Goods goods1 : result) {
                String statusString = "";
                if (goods1.getBargainStatus() == 1) {
                    statusString = "待上架";
                } else if (goods1.getBargainStatus() == 2) {
                    statusString = "审核中";
                } else if (goods1.getBargainStatus() == 3) {
                    statusString = "审核通过";
                } else if (goods1.getBargainStatus() == 4) {
                    statusString = "审核不通过";
                } else if (goods1.getBargainStatus() == 5) {
                    statusString = "活动开始";
                } else if (goods1.getBargainStatus() == 6) {
                    statusString = "活动结束";
                } else if (goods1.getBargainStatus() == 7) {
                    statusString = "下架";
                }
                BargainDTO bargainDTO = new BargainDTO()
                        .setGoodsNo(goods1.getGoodsNo())
                        .setGoodsName(goods1.getName())
                        .setActivityPrice(String.valueOf(goods1.getBargainPrice()))
                        .setActivityStock(String.valueOf(goods1.getBargainStore()))
                        .setSaleNumber(String.valueOf(goods1.getBargainSalesVolume()))
                        .setTime(goods1.getBeginDateOfValidity() + " - " + goods1.getEndDateOfValidity())
                        .setStatus(statusString);
                data.add(bargainDTO);
            }

            ExcelUtil.writeExcel(response, data, "特价活动" + Dates.transDateToStr(new Date()), "sheet", new BargainDTO());

        } catch (Exception e) {
            log.error("[导出异常]", e);
        }
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

        model.addAttribute("goods", goods);

        return "mall/marketing/bargain/detail";

    }

    /**
     * 审核页面
     */
    @RequestMapping(value = "/{id}/process", method = RequestMethod.GET)
    private String process(Model model, @PathVariable("id") long id) {
        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        model.addAttribute("goods", goods).addAttribute("_method", "PUT");
        return "mall/marketing/bargain/check";
    }

    /**
     * 审核特价活动
     */
    @RequestMapping(value = "/{id}/process", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> process(HttpServletRequest request, Goods params) {

        try {
            goodsApplication.bargainProcess(params);
            logApplication.eventOfSystem(Securitys.currentUser(), "审核特价活动" + params.getName(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[审核特价活动异常]", e);
            return ImmutableMap.of("status", false);
        }
    }


    /**
     * 下架特价活动
     */
    @RequestMapping(value = "/{id}/soldout", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> process(HttpServletRequest request, @PathVariable long id) {

        try {
            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

            goodsApplication.soldoutBargain(goods);
            logApplication.eventOfMerchant(Securitys.currentUser(), "下架特价商品", Securitys.getIp(request));
            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            log.error("[下架特价活动异常]", e);
            return ImmutableMap.of("status", false);
        }
    }


    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Goods goods) {

        if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getId() > 0) {
            goods.setGoodsChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getId() > 0) {
            goods.getGoodsChannel().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getParent().getId() > 0) {
            goods.getGoodsChannel().getParent().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getParent().getId());
        }

        if (StringUtils.isNotBlank(goods.getDate())) {
            sql += " and u.beginDateOfValidity > :beginTime and u.endDateOfValidity < :endTime";
            params.put("beginTime", goods.getDate().substring(0, 10));
            params.put("endTime", goods.getDate().substring(13));
        }


        if (goods.getBargainStatus() > 0) {
            sql += " and u.bargainStatus = :status ";
            params.put("status", goods.getBargainStatus());
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo = :goodsno ";
            params.put("goodsno", goods.getGoodsNo());
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + goods.getName() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.bargainPrice " + goods.getOrderByPrice();
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.bargainStore " + goods.getOrderByStore();
        }

        if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        }

        return sql;
    }

}
